//
//  OAuthViewController.swift
//  WeiBo
//
//  Created by tusm on 2017/6/23.
//  Copyright © 2017年 GM. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {

    var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view = webView
        
        webView.delegate = self

        view.backgroundColor = UIColor.white
        
        navigationItem.title = "微博登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.closedOAuthView))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(OAuthViewController.autoFill))
        
        self.webView.loadRequest(URLRequest(url: NetworkTools.shareTools.oauthURL))
    }
    

 }


// MARK: - 点击方法
extension OAuthViewController{
    
    
    /// 自动填充
    func autoFill(){
        
        let js = "document.getElementById('userId').value = '13627213760';" + "document.getElementById('passwd').value = 'gui99199760';"
        
        webView.stringByEvaluatingJavaScript(from: js)
        
    }
    
    
    /// 关闭视图
    func closedOAuthView(){
        
        dismiss(animated: true, completion: nil)
    }
}


// MARK: - UIWebViewDelegate方法----取得用户信息
extension OAuthViewController:UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //1.
        guard let url = request.url, url.host == "www.baidu.com" else {
            
            return true
        }
        
        guard let query = url.query, query.hasPrefix("code=") else {
            print("取消登录")
            
            return false
        }
        
        //print(url.query as Any)
        
        let code =  query.substring(from: "code=".endIndex)
        
        UserAccountViewModel.shareUserAccount.loadAccessToken(code: code) { (isSuccessed) in
            
            if isSuccessed{
                print("成功了")
                print(UserAccountViewModel.shareUserAccount.account!)
            }else{
            
            print("出错了")
                
            }
        }
        
        
        return true
    }
    
 
    
}
